/*
 * @Description: 层级匹配设置
 * @Author: Zzt
 * @Date: 2022-11-05 17:20:14
 * @LastEditTime: 2023-01-30 16:50:45
 */

import { Button, Form, Select, Space, Table } from 'antd';
import Column from 'antd/es/table/Column';
import { v4 as uuidv4 } from 'uuid';
import { jsonClone } from '@/utils';
import { useEffect, useState } from 'react';
import { delItemById, editItemById, getListItemValue } from '@/utils/list';
import { IArchiveType, ILevel } from '@/interfaces/archiveType';
import { useMappingRelationContext } from '../../../contexts/MappingRelationContext';
import { fetchATListByFondId } from '@/api/archivesType';
import { searchFetchFields } from '@/api/metadata';

const { Option } = Select;

class ExcelItem {
  key: string;

  typeTitle: string = null;

  title: string = null;

  constructor(idx: number) {
    this.key = uuidv4();
  }
}

const HierarchyTAT = (props: any) => {
  const { onChange } = props;
  const { hierachy, base } = useMappingRelationContext();
  const { description } = base;
  console.log('hierachy', hierachy, base);
  // 档案类型列表
  const [ATList, setATList] = useState<IArchiveType[]>([]);
  // 表格内容
  const [initTable, setInitTable] = useState([]);
  const [afterType, setAfterType] = useState([]);
  const [beforeType, setBeforeType] = useState([]);

  useEffect(() => {
    setInitTable(hierachy);
  }, []);

  useEffect(() => {
    if (description) {
      fetchATListByFondId(description).then((res) => {
        const _atList: IArchiveType[] = res.data;
        console.log(_atList);
        setATList(_atList);
      });
    }
  }, [description]);

  useEffect(() => {
    if (base && ATList.length > 0) {
      const beforelevel = ATList.find((item) => item.id === base.before);
      console.log(beforelevel);
      const param = {
        archiveTypeId: beforelevel.id,
        atCode: beforelevel.atCode,
        atType: beforelevel.atType,
        level: [1]
      };
      searchFetchFields([{ ...param }]).then((res) => {
        const { data } = res;
        setBeforeType(data);
      });
      const afterlevel = ATList.find((item) => item.id === base.after);
      console.log(afterlevel);
      const params = {
        archiveTypeId: afterlevel.id,
        atCode: afterlevel.atCode,
        atType: afterlevel.atType,
        level: [1]
      };
      searchFetchFields([{ ...params }]).then((res) => {
        const { data } = res;
        setAfterType(data);
      });
    }
  }, [base, ATList]);
  const deleteItem = (key: string) => {
    setInitTable(delItemById(key, initTable, 'key'));
  };
  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    console.log('row的值', row);

    const newData = jsonClone(initTable);
    const index = newData.findIndex((item: any) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setInitTable(newData);
    onChange(newData);
  };
  return (
    <>
      <Space align="baseline">
        <b>层级匹配列表</b>
        <Button
          onClick={() => {
            setInitTable((state) => [...state, new ExcelItem(state.length)]);
          }}
        >
          添加一行
        </Button>
      </Space>
      <p>在列表内配置源档案层级和目标档案类型层级的对应关系。（按层级最高到最低依次选择）</p>
      <Table dataSource={initTable} size="small" pagination={false} bordered>
        <Column
          title="序号"
          key="idCol"
          align="center"
          render={(_val, _record, idx) => `${idx + 1}`}
        />
        <Column
          title="源档案类型层级"
          dataIndex="beforeType"
          key="beforeType"
          align="center"
          render={(val, record: ILevel) => (
            <Select
              value={val}
              style={{ width: 200 }}
              placeholder="请选择字段"
              size="small"
              onChange={(value) => {
                handleSave({
                  ...record,
                  beforeType: value,
                  beforeTypeName: beforeType.find((item) => item.field_name === value).field_desc
                });
              }}
            >
              {beforeType.map((item: any) => (
                <Option key={item.field_name} value={item.field_name}>
                  {item.field_desc}
                </Option>
              ))}
            </Select>
          )}
        />
        <Column
          title="目标档案类型层级"
          dataIndex="afterType"
          key="afterType"
          align="center"
          render={(val, record: any) => (
            <Select
              value={val}
              style={{ width: 140 }}
              size="small"
              placeholder="请选择字段"
              onChange={(value) => {
                handleSave({
                  ...record,
                  afterType: value,
                  afterTypeName: afterType.find((item) => item.field_name === value).field_desc
                });
              }}
            >
              {afterType.map((item: any) => (
                <Option key={item.field_name} value={item.field_name}>
                  {item.field_desc}
                </Option>
              ))}
              {/* {items.map((item: any) => (
                  <Option key={item.field_name} value={item.field_desc}>
                    {item.field_desc}
                  </Option>
                ))} */}
            </Select>
          )}
        />
        <Column
          title="操作"
          dataIndex="action"
          key="action"
          align="center"
          render={(_val, record: any) => (
            <Button
              type="link"
              size="small"
              danger
              onClick={() => {
                deleteItem(record.key);
              }}
            >
              删除
            </Button>
          )}
        />
      </Table>
    </>
  );
};
export default HierarchyTAT;
